package com.wy.classloader;

import aj.org.objectweb.asm.*;

public class AnnotationReplacer {
    public static byte[] modifyClassBytes(byte[] classBytes) {
        ClassReader classReader = new ClassReader(classBytes);
        ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);

        ClassVisitor classVisitor = new ClassVisitor(Opcodes.ASM7, classWriter) {
            @Override
            public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
                MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature, exceptions);
                return new MethodVisitor(Opcodes.ASM7, methodVisitor) {
                    @Override
                    public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
                        if (desc.equals(Type.getDescriptor(QmConsumerAdapter.class))) {
                            // 替换注解
                            AnnotationVisitor annotationVisitor = super.visitAnnotation(Type.getDescriptor(ConsumerAdapter.class), visible);

                            // 属性替换 topic 换成partition
                            return new AnnotationVisitor(Opcodes.ASM7, annotationVisitor) {
                                @Override
                                public void visit(String name, Object value) {
                                    // 修改注解的属性
                                    if (name.equals("topic")) {
                                        name = "partition";
                                    }
                                    super.visit(name, value);
                                }
                            };
                        }

                        return super.visitAnnotation(desc, visible);
                    }
                };
            }

        };

        classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES);

        return classWriter.toByteArray();
    }

}